#dotenv package nodejs
Explore tagged Tumblr posts
Text
Access Environment Variable in Nodejs JavaScript Application | Reading ENV Variable Example
Full Video Link https://youtu.be/dxrNopL1sbQ Hello friends, new #video on #reading #accessing #environmentvariables in #nodejs #projeect #application #tutorial #examples is published on #codeonedigest #youtube channel. @java #java #aws #a
In this video, we will read the environment variable in nodejs javascript project. We will learn what “dotenv” module in nodejs javascript. How to use “dotenv” package in our nodejs javascript project. ** Important Nodejs Javascript Packages or Modules ** Dotenv – DotEnv is a lightweight npm package that automatically loads environment variables from a .env file into the process.env object. To…
View On WordPress
#dotenv#dotenv example#dotenv in node js#dotenv module#dotenv module in node js#dotenv module not found#dotenv nodejs#dotenv package#dotenv package install#dotenv package nodejs#dotenv package.json#dotenv tutorial#dotenv tutorial nodejs#environment variable#environment variables#javascript environment variable#linux environment variables#node js javascript#node js javascript tutorial#nodejs#python environment variables#set environment variables
0 notes
Text
Thử viết một command tool bằng NodeJS và publish lên npmjs.com
Intro
Các bạn có biết tại sao Node.js hay rộng hơn là Javascript nó phát triển mạnh mẽ và cộng đồng phát triển nó lớn vậy không?
Một trong những nguyên nhân là sự phát triển rất dễ dàng các thư viện, framework và publish lên cộng đồng, cụ thể chính là npm với trang npmjs.com
Hôm nay mình xin sẽ tận tay chứng minh tại sao nó lại dễ đến vậy với việc mình thử viết command tool (cli) **và **publish lên npmjs.com nó đơn giản như thế nào.
const path = require('path') const env = process.env.NODE_ENV === 'production' ? 'production.env' : '.env' require('dotenv').config({ path: path.join(__dirname, env) })
Xin thưa, mình để ảnh này vào cho đỡ chống
1. Ý tưởng
Mình đang có 1 task mình đang phải làm hàng ngày là review các node package và publish project đó lên npmjs.com. Công việc đó lặp đi lặp lại hàng ngày và mình thấy rất nhàm chán và tốn thời gian nên mình đã quyết định dành ra 1 buổi để ngồi viết 1 cái tool để gõ đúng 1 lệnh làm tất cả mọi thứ. Việc của mình chỉ là ung dung ngồi đợi nó làm xong việc. Easy!
2. Lấy yêu cầu
Đầu tiên mình sẽ liệt kê yêu cầu của command line tool sẽ phải làm gì?
Kiểm tra project là git folder và đang ở nhánh develop, nếu không đang ở nhánh develop phải chuyển về nhánh develop.
Kiểm tra project là một node package
Tăng version cho package đó và commit file vừa sửa đổi và push lên develop
Merge code từ develop vào master
Publish project đó lên npmjs.org (lưu ý là phải hỗ trợ cả private packages)
Quay trở lại nhánh develop ở trạng thái bình thường.
3. Triển khai
Đầu tiên mình cần đặt tên cho package của mình, mình kiểm tra trên npmjs.com xem tên package có available hay không và mình quyết định đặt tên package là: my-publisher và command line sau khi cài xong sẽ có lệnh là publish (mình không muốn đặt lệnh dài dòng nên để tên vậy).
Ok, đã có tên, mình bước ngay vào việc tạo 1 project node với lệnh:
npm init
Tiếp theo mình cần xử lý đến input đầu vào qua command line, và mình sử dụng meow vì nó khá dễ dùng và tiện lợi. Mình chỉ cần khai báo các options là có ngay 1 cli với việc xử lý input đầu vào đầy đủ.
Tiếp theo mình cần xử lý các script mình đã liệt kê ở phần 2 với việc chạy các lệnh và mình quyết định sử dụng execa để run các lệnh. Package này khá dễ dùng và hỗ trợ promise, tiện hơn rất nhiều nếu mình dùng **child_process** của Node core. Phần này đã tốn mất ít nhất 4 tiếng của mình để implement các lệnh này sang dạng code.
Ngoài ra mình có sử dụng thêm simple-git để xử lý các tác vụ liên quan đến git.
Ok! Cơ bản mình đã có phần core đầy đủ để biến project mình thành 1 command tool. Giờ mình cần biến nó thành 1 command tool thực thụ. Để biến 1 project node thành 1 command tool thì npm có 1 trường bin trong file package.json cho phép khai báo các command muốn cài đặt vào biến môi trường.
"bin": { "publish": "bin/index.js" }
Ví dụ như trong project này, mình đã tạo 1 file bin/index.js để khi chạy lệnh publish nó sẽ gọi đến file này.
Bước cuối cùng của mình sẽ cần publish package này lên npmjs.com. Việc này cực kì đơn giản, bạn chỉ đơn giản đăng ký 1 tài khoản trên npmjs.com. Rồi chạy lệnh npm login ở dưới máy. Sau đó quay trở lại project hiện tại và chạy lệnh:
npm publish --access public
và chờ nó publish lên npmjs.com
4. Thành quả
Sau khi đã publish lên npmjs.com có nghĩa là bạn đã chính thức vừa trở thành một contributor cho cộng đồng npmjs.com. Vỗ tay nào!
Việc đơn giản bây giờ là cài đặt package về máy với lệnh cực kỳ đơn giản:
npm i -g my-publisher
Sau đó trên máy có thể dùng ngay lệnh publish và ngồi rung đùi chờ mọi thứ tự động chạy. Easy!
Đây là thành quả mình đã thử với my-publisher của mình
Các bạn có thể tham khảo project của mình tại đây: https://github.com/tutv/my-publisher
4. Mở rộng
Thường việc chạy các command tool thường sẽ mất thời gian và cần phải hiện ra tình trạng đang chạy đến phần nào, có lỗi hay không. Để làm việc đó, mọi người đơn giản sẽ dùng console của NodeJS cung cấp để hiển thị ra mọi thông tin đang chạy đúng không? Nhưng ở đây mình đã tìm ra thêm 1 thứ khá hay ho là cách để tạo ra các lệnh và có spinner hay loading để hiện thị task đang chạy thay vì thô cứng với việc hiển thị text qua console. Và đó chính là nhờ **ora**, các bạn có thể xem demo nó như thế này:
Hiệu ứng loading với command line
5. Kết luận
Với các công cụ, thư viện có sẵn trên npmjs.com mình đã nhanh chóng hoàn thành xong 1 command tool **bằng NodeJS và publish nó lên **npmjs.com. Việc của mình chỉ cần tập trung vào việc viết phần chính của command tool. Các bạn có thể thử ngay và thỏa sức sáng tạo với ý tưởng của chính mình nhé.
Hãy để lại bình luận nếu các bạn đã viết được command tool nào của chính mình nhé.
1 note
·
View note
Text
Top Nodejs Security Practices
Since it bridges the gap between front-end and back-end applications, Node.js is widely used today in web and mobile applications. Unfortunately, the increased use of Node.js has given attackers new opportunities to exploit misconfigurations and vulnerabilities.
The developers have a huge responsibility to improve application security to prevent these attacks. As a result, in this article, I'll go over the 5 best practices for enhancing safety in your Node.js application.
Top 5 Nodejs Security Practices
Validate User Inputs Injection-based attacks have made it into the OWASP and SANS Top 25 CWE lists, and they can take many different forms. Validating all inputs before processing data is critical for avoiding these attacks. For instance, the phone number field should only accept a specific numeric and special character format.
Adding a layer of security with a Reverse Proxy A reverse proxy is a security layer that allows a server to access a web application. The server filters requests and ensures that it does not become overburdened. We can set a rate limit on the proxy configuration and implement connection timeouts.
Keeping track of application secrets We should use standard methods to store application secrets because they are essential. This information can be stored in operating system environment variables, and the dotenv package is the best way to manage secrets when multiple variables need to be instantiated.
Using Security Linters to Identify Code Vulnerabilities Before compiling, code linters assist developers in identifying various issues in the code. They can detect the most common problems and force programmers to adhere to best practices. These code linters have their own rules that developers can tweak to fit their needs. As a result, developers must enable them in the linter configuration before using the security vulnerability detection rules.
Data leakage prevention You can't rely on what you get from the front end, and you shouldn't rely on the data you'll be sending. You can send all of the information for the specific object to the front end and filter what will appear there. It's easy to do because hackers always look for hidden data sent from the back-end. In this case, the best solution is only to consider sending the required information. If the first and last names are required, they are only retrieved from the database. It is common to do extra work, but it is well worth the effort.
Conclusion
We looked at the best practices for Node.js security in 2021 and the years ahead. It is critical to secure and precisely safeguard web applications. On the other hand, people do not implement security measures regularly and forget to do so when there are tight project deadlines.
Consider Node.js Security solutions at each stage of the software development life cycle to ensure there are no additional security risks from conception to production.
0 notes
Text
How to Build Microservices with Node.js
Divide into independent chunks to build the entire application.
Introduction
In the last blog, we learned about Microservice Architecture and Why Build Microservices with Node.js. If you haven’t explored or read much about Microservice Architecture then I would recommend visiting our last blog, to have basic theoretical knowledge. The blog deals with What, Why, and When with Microservices. We will cover the remaining question ‘How’ in this tutorial.
You are exactly right! In this tutorial, we will learn how to build a basic demo application for illustrating Microservices with Node.js. The tutorial will consist of basic and simple steps that you can follow with us and start building your own demo app.
Without further ado, let’s get started with our application.
Microservices with Node.js Example
In this demo application, we will build microservices with NodeJS which will connect to an external API.
The app will have three services: Book, Customer, and Order services. Each of the services will have individual servers running on different ports. These services will communicate with each other through REST APIs. We all know that if it wasn’t microservices architecture we would have only one server running. But, in microservices architecture the scenario is different.
So, this was about what we are building in this tutorial, let’s get started with the coding part.
Initial Set-Up
Make sure you have Node.js installed. Visit Nodejs.org to download the latest Node version, if your system doesn’t have Node.js.
Run npm init in the project root folder. This will create a package.json file that will create certain questions about the package, if you are not sure how to respond you can use the default.
We will use four packages, Express, mongoose, axios, and dotenv which can be installed as follows:
$ npm install express mongoose axios dotenv --save
Project Structure
Refer to the below image for the project structure. The structure can vary from person to person.
Read more: Creating Database Connection
0 notes
Link
This blog post is Part 2 of the blog post series on Building Real-Time TV Dashboards with Salesforce Data, Platform Events & a Raspberry Pi. Part 1 – The Intro Part 2 – Salesforce Setup Part 3 – Raspberry Pi Setup Let’s get started with the Raspberry Pi setup. The idea is to have the Dashboard running on the Pi. This can be done in various different ways but for the sake for this project we will be hosting and running the dashboard on the Raspberry Pi. We will be building the Dashboard using the LWC OSS (Lightning Web Components Open Source) Framework. Pro Tip (Optional but totally worth trying out): Setup SSH and VNC on the Pi for super easy remote development and remote control. Step 0: Install the OS (Skip this step if you already have the OS installed) I am using Raspbian OS on my Pi and I set it up using NOOBS – New Out Of the Box Software and it makes the installation very easy. Here is a comprehensive step by step guid on installing the OS using NOOBS – https://www.raspberrypi.org/help/noobs-setup/2/ Step 1: Disable the Screensaver This is an important step because by default the PI’s screen keeps blanking out every 15 mins. As we will be having a standalone realtime dashboard running on the PI, we need to have our screensaver disabled. Easiest way to get this done is by installing xscreensaver. In the Terminal, run the following command to install it. This might take a few minutes $ sudo apt-get install xscreensaver Once installed, go to Preferences option in the main desktop menu. You should find the screen saver application. Launch it and search for the option to disable it completely. Step 2: Install Node.js Run the following commands in the Terminal Update your system package list sudo apt-get update Upgrade all your installed packages to their latest version sudo apt-get dist-upgrade Download the latest version of Node.js curl -sL https://deb.nodesource.com/setup_12.x | sudo -E bash - Install it sudo apt-get install -y nodejs To check if the installation was successful, run the following command and it should return the version number of Node.js node -v Step 3: Create LWC App The Dashboard Interface is an LWC App. So, the goal is to have an LWC App running on the Raspberry Pi and it is totally up to you on how and where you build the LWC app. As long as there is an LWC App to be run on the Pi, you can either develop it on the Pi or develop it somewhere else(like your local machine) and migrate it to the Pi. For example, I developed it on my local machine and pushed it to the Pi via version control(bitbucket) so that I could maintain a backup and also sync code changes between my system and the pi. Feel free choose which ever way you are comfortable with and make sure you have Node.js installed as it is required to develop and run LWC Apps. 3.1 Create tv-dashboard LWC App On the command line/terminal, run command: npx create-lwc-app tv-dashboard When prompted about the application details, fill in the details as following Package name for npm: Press Enter to accept the default Description: Type the app description or press Enter to accept the default Author: Type your name or press Enter to accept the default Version: Press Enter to accept the default License: Press Enter to accept the default Who is the GitHub owner of the repository ( https://github.com/OWNER/repo): Type in your GitHub owner name or leave it blank and press Enter What is the GitHub name of the repository ( https://github.com/owner/REPO): Type in your GitHub repo name or Press Enter to accept the default Select a package manager: Use your arrow keys to select npm press Enter Use TypeScript or JavaScript: Use your arrow keys to select JavaScript press Enter Use custom Express server configuration: Enter y to install the server and press Enter Once the application is created, you will see the following message: Created conference-app in /YOUR/FILE/STRUCTURE/tv-dashboard. Checkout the `scripts` section of your `package.json` to get started. 3.2 Install A Few Packages Open command line/terminal Navigate to the directory containing the tv-dashboard application cd tv-dashboard Run the following command: npm install jsforce dotenv socket.io chart.js @salesforce-ux/design-system But, what are these applications and why do we need them? jsforce – JavaScript library to interact with Salesforce Orgs and APIs dotenv – To store our Salesforce credentials as environment variables in a .env file and reference them in or app socket.io – JavaScript library that enables real-time bidirectional event-based communication. We are using this to communicate our platform events from the LWC Server to LWC Frontend(charts). Works in a pub-sub model. chart.js – JavaScript library to create simple and beautiful HTML5 charts using canvas elements @salesforce-ux/design-system – Salesforce Lightning Design System (SLDS) – CSS framework to make our app beautiful 3.3 Create the .env file and declare our salesforce credentials as environment variables Open the tv-dashboard application folder Create a file with .env (with a leading period) as file name. Make sure that you are creating this folder in the root folder i.e., tv-dashboard Add the following the content into the .env file .env SF_LOGIN_URL=https://login.salesforce.com SF_USERNAME=YOUR_USERNAME SF_PASSWORD=YOUR_PASSWORD SF_TOKEN=YOUR_SECURITY_TOKEN Make sure to update the above placeholder values with your data SF_USERNAME: Your Salesforce Org’s username. SF_PASSWORD: Your Salesforce Org’s password. SF_TOKEN: Your Salesforce Org’s security token. 3.4 Update lwc-services.config.js to use the Lightning Design System SLDS In the tv-dashboard application folder, open the scr folder Open the file lwc-services.config.js Add the following in the resources section of your config { from: 'node_modules/@salesforce-ux/design-system/assets', to: 'dist/resources/assets' } 3.5 Add LWC Express Server Code In the tv-dashboard application folder, open folder server Open the file index.js Add the following code at the beginning of the file (before the line module.exports) src/server/index.js console.log(`Running server on port ${PORT}`)); // Start backend server server.listen(PORT, openDashboard); function openDashboard() { console.log(`Running socket server on port ${PORT}`); if (npm_lifecycle_event === 'serve') { console.log('Launching Dashboard!!'); exec( 'chromium-browser --noerrdialogs --kiosk http://0.0.0.0:3002 --incognito --disable-translate' ); } } 3.6 EDIT Client INDEX.html to add SLDS Stylesheet In the tv-dashboard application folder, open folder client Open the file index.html Replace the file content with the following code /src/client/index.html 3.7 Edit Client INDEX.js to use Synthetic Shadow DOM for the app and components to be able to use SLDS In the tv-dashboard application folder, open folder client Open the file index.js Add the following code at the beginning of the file content import '@lwc/synthetic-shadow'; 3.8 Create LWC Chart Component for visualising Opportunity Count By their Stage In the tv-dashboard application folder, open the folder my Create a folder named opportunitiesByStage Inside opportunitiesByStage folder, create a file opportunitiesByStage.html with the following content /src/client/modules/my/opportunitiesByStage.html Inside opportunitiesByStage folder, create a file opportunitiesByStage.js with the following content /src/client/modules/my/opportunitiesByStage.js import { LightningElement, api, track } from 'lwc'; export default class opportunitiesByStage extends LightningElement { @api sobject = ''; @api socket; @track socketInitialized = false; @track chartInitialized = false; chart; //object to keep track of the number of opportunities per stage chartData = {}; chartConfig = { type: 'doughnut', data: { datasets: [ { data: [], backgroundColor: [ '#3296ED', '#9D53F2', '#E287B2', '#26ABA4', '#77B9F2', '#C398F5', '#4ED4CD' ] } ], labels: [] }, options: { responsive: true, elements: { arc: { borderWidth: 0 } }, legend: { position: 'right', labels: { usePointStyle: true } }, animation: { animateScale: true, animateRotate: true } } }; async renderedCallback() { if (!this.socketInitialized && this.socket) { this.initializeSocket(); } if (!this.chartInitialized && this.socketInitialized) { await this.initializeChart(); } } initializeSocket() { //bind the onSocketEvent method to the 'cdc' socket event to update the chart with new incoming data this.socket.on('cdc', this.onSocketEvent.bind(this)); this.socketInitialized = true; } //initialize chart with chart.js async initializeChart() { await require('chart.js'); const ctx = this.template .querySelector('canvas.chart') .getContext('2d'); this.chart = new window.Chart(ctx, this.chartConfig); this.chartInitialized = true; } onSocketEvent(data) { const { changeType, entityName } = data.ChangeEventHeader; // check to make sure the change event is for the configured sobject and the record event is CREATE if ( this.sobject.toLowerCase() !== entityName.toLowerCase() || changeType !== 'CREATE' ) { return; } //update the chartData to increment the corresponding opportunity stage counter this.chartData[data.StageName] = this.chartData[data.StageName] + 1 || 1; //sort chartData in descending order let sortable = Object.entries(this.chartData); sortable.sort(function(a, b) { return b[1] - a[1]; }); //update chartData with sorted data this.chartData = Object.fromEntries(sortable); //add the updated data to the chart object this.chart.data.labels = Object.keys(this.chartData); this.chart.data.datasets[0].data = Object.values(this.chartData); //update the chart to reflect latest data this.chart.update(); } } 3.9 Create an LWC Component to view Chatter Announcements In the tv-dashboard application folder, open the folder my Create a folder named chatterAnnouncement Inside chatterAnnouncement folder, create a file chatterAnnouncement.html with the following content /src/client/modules/my/chatterAnnouncement.html Inside chatterAnnouncement folder, create a file chatterAnnouncement.html with the following content /src/client/modules/my/chatterAnnouncement.js 12 ? hour - 12 : hour; hour = this.formatNumber(hour); min = this.formatNumber(min); sec = this.formatNumber(sec); this.time = `${hour}:${min} ${ap}`; const months = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ]; const days = [ 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday' ]; const curWeekDay = days[today.getDay()]; const curDay = today.getDate(); const curMonth = months[today.getMonth()]; const curYear = today.getFullYear(); this.date = `${curWeekDay}, ${curDay} ${curMonth}, ${curYear}`; this.dateTime = `${this.date} • ${this.time}`; } formatNumber(num) { return num < 10 ? '0' + num : num; } } 3.10 Edit the App Component to add the Chart and the Chatter Announcements Components and also subscribe to our Socket.io server In the tv-dashboard application folder, open the folder app Open the file app.html and replace its content with the following /src/client/modules/my/app.html Open the file app.js and replace its content with the following code to initialise and subscribe to the backend socket server /src/client/modules/my/app.js { console.log('socket connected!'); this.socketReady = true; }); } async closeSocket() { this.socket.close(); this.socket = null; } } Step 4: Run The Dashboard We run the dashboard on chromium in kiosk mode, this helps show the in dashboard full screen. You can run the dashboard using the following command npm run build && npm run serve If you are developing, making code changes and would like for them to reflecting in real time, use the command npm run watch Note: Only the npm run serve command launches the Dashboard automatically. When using the npm run watch command, you would need manually view the app in the browser. Once you run the dashboard, start creating some Opportunities and Chatter Announcements in your org and you will see the Dashboard update in real-time! Step 5 (Optional): Auto Launch the Dashboard on Raspberry Pi Startup 5.1 Change the LWC Dashboard App Folder Permissions This wouldn’t be necessary if you are created everything on the pi. But when I used Git to sync code, I came across a the EACCESS Permission error and this following terminal command took care of the error. sudo chown -R pi:pi ABSOLUTE_PATH_TO_LWC_APP_FOLDER Make sure to replace the ABSOLUTE_PATH_TO_LWC_APP_FOLDER with the actual absolute path of your Dashboard LWC App folder. To get the absolute path, right click your Dashboard LWC App folder and Select Copy Path(s) 5.2 Create a executable shell script file Open the tv-dashboard folder Create a file with name run.sh and add the below as its content run.sh #!/bin/bash cd ABSOLUTE_PATH_TO_LWC_APP_FOLDER npm run build && npm run serve Make sure to replace the ABSOLUTE_PATH_TO_LWC_APP_FOLDER with the actual absolute path of your Dashboard LWC App folder. To get the absolute path, right click your Dashboard LWC App and Select Copy Path(s) 5.3 Edit the Raspberry Pi Autostart Script Open Terminal Run the following command sudo nano /etc/xdg/lxsession/LXDE-pi/autostart Add the following line to the file @lxterminal --command "ABSOLUTE_PATH_TO_SHELL_SCRIPT_FILE" Make sure to replace the ABSOLUTE_PATH_TO_SHELL_SCRIPT_FILE with the actual absolute path of the shell script created(in the previous step) inside the Dashboard LWC App folder. To get the absolute path, right click the shell script file that you created(in the pervious step) inside the Dashboard LWC App and Select Copy Path(s) Hit Control+S to Save Then Control+X to Exit the editor And… that is it! We learnt how to go about Build Real-Time TV Dashboards with Salesforce Data, Platform Events & a Raspberry Pi. We’ve scratched the surface with just 2 components and here is the tv-dashforce GitHub Project that not only contains the components created in this blog post but also different chart components along with Twitter Live Stream, Clock, Weather and Holidays. Make sure to check it out! GitHub Project- https://github.com/Minerva18/tv-dashforce This can also be done in another way where, we can host the Dashboard LWC App on the cloud like Heroku/AWS/Google etc. and use the URL to show the Dashboard LWC app via chromium kiosk mode on the Raspberry Pi. Raspberry Pi Resources https://www.raspberrypi.org/ What is a Raspberry Pi? https://www.raspberrypi.org/help/what-%20is-a-raspberry-pi/ Raspberry Pi Documentation and Setup Guides https://www.raspberrypi.org/documentation/ Installing OS https://www.raspberrypi.org/documentation/installation/noobs.md SSH Setup Guide https://www.raspberrypi.org/documentation/remote-access/ssh/ VNC Setup Guide https://www.raspberrypi.org/documentation/remote-access/vnc/ Screensaver https://www.raspberrypi.org/documentation/configuration/screensaver.md Securing your Raspberry Pi https://www.raspberrypi.org/documentation/configuration/security.md LED warning flash codes https://www.raspberrypi.org/documentation/configuration/led_blink_warnings.md The post Build Real-Time TV Dashboards with Salesforce Data, Platform Events & a Raspberry Pi – Part 3 – Raspberry Pi Setup appeared first on Minerva18.
0 notes
Text
Moving from NodeJS to Go
The approach of this article is this:
You are a seasoned NodeJS developer, and are looking to learn a new language, but you don't want to go deep, just see how things compare with your current expertise, and then make a final decision.
Chances are, you were initially a PHP developer, then you found your way into NodeJS and now you feel like you want to expand your expertise. Of course I might be wrong, but in this article we are going to look at some common patterns when working with NodeJS and how they compare in Go.
Since this is a NodeJS to Go comparison, we're going to focus on language constructs and servers. We'll break it down like this:
The most common reasons to learn Go include the following:
We see that Go has only 25 keywords, and this can give you a clue on how simple it is to learn the language. We'll also be looking at the common language patterns, and we'll see how cleaner and easier it is to do some common tasks as compared to other languages. The standard library that comes with Go also has a lot of built in functionality, that you will find yourself rarely relying on other external libraries. Go code will not compile if you have unused variables or syntax errors.
Here's an example with the net/http package that we'll use later. You can see examples are provided, and there are even tabs for the source code files. Sweet!
Is Go Better Than JavaScript ?. No, I don't think so, nor do I think JavaScript is better. The idea is to use the right tool for the job, and sometimes, one tool is better than another one, or one developer is better in one tool over another. So learn what you can, and choose the right thing that you are sure will get the job done for you.
We'll look at a few language constructs that we are used to.
Here's a hello world program in NodeJS
console.log('Hello World');
Running this will produce Hello World in the terminal.
node app.js
Here's an equivalent hello world program in Go
package main import "fmt" func main() { fmt.Println("Hello World") }
What we'll notice first, is that Go follows a certain structure which involves: This code can be run by typing in the following, or see it in GoPlay Space.
go run main.go
where main.go is the name of the file.
JavaScript is dynamically typed, which means you do not have to specify types when defining variables, and the variables can change their types as you program along.
That being said, JavaScript has the following types:
To define variables in JavaScript(NodeJS) we'd write this:
const num = 3; let flt = 2.34; let a = true; let b = false; var name = 'Scotch';
Go however, is statically typed, which means we have to define the types before hand, or assign them and let them be inferred. Here's a comprehensive list of Go Types.
An equivalent of the above JavaScript definitions in Go is
package main const num = 3 func main() { var flt float64 = 2.34 var name string = "Scotch" a, b := 2.34 // shorthand declaration syntax }
Assigning initial values in Go is done by with the var keyword, a variable name, and a type. Additionally and more commonly the := shorthand syntax can be used. When declaring variables with := , they are automatically assigned the correct type. The shorthand declaration syntax can only be used within a function. Finally, you can assign multiple values in one line like we have done in a, b := true, false. This will assign both a and b to the right hand values respectively.
Here is an array of strings in JavaScript
const names = ['Scotch', 'IO'];
While Go has arrays, what we typically refer to arrays in JavaScript are referred to as slices in Go. Here's an example of a slice in Go:
package main func main() { names := []string{"Scotch", "IO"} }
As an example, we'll write a small program that returns the substring of a string at index 10. So a sentence like Luke, I'm not your father will end up being Luke, I'm
JavaScript
const sentence = '`Look, I\'m not your Father';` console.log(sentence.substr(0,10));
Go
package main import "fmt" func main() { sentence := "Look, I'm not your Father" fmt.Println(sentence[:10]) }
You can run the app in Goplay Space
Conditional statements include if else and switch statements. Here's an example in NodeJS.
const age = 10; if (age > 10) { console.log('You are old'); } console.log('you are young'); const gender = 'female'; switch(gender) { case 'female': console.log('your name is tonie'); break; case 'male': console.log('your name is tony'); break;; default: /// }
Here's a equivalent Go
package main import "fmt" func main() { age := 10 if age > 10 { fmt.Println("You are old") } fmt.Println("You are young") gender := "female" switch gender { case "female": fmt.Println("Your name is tonie ") case "male": fmt.Println("Your name is tony") default: /// } }
You can run the app in GoPlay Space.
You'll notice the conditionals are a bit cleaner in Golang, with less brackets.
JavaScript has 3 loops: for loop, while loop, and a do while loop. Here's a for loop example.
// normal for loop for i = 0; i < 10; i++ { console.log(i); } // key, value loop for (var key in p) { if (p.hasOwnProperty(key)) { console.log(key + ' -> ' + p[key]); } } // another key value loop Object.keys(obj).forEach(function(key) { console.log(key, obj[key]); }) // there's also a `for...of`
Go has only one type of loop, and it's the for loop. Don't let that deceive you though as the for loop in Go is very versatile and can emulate almost any type of loop. Let's look at a simple example:
package main import ( "fmt" ) func main() { for i := 0; i < 10; i++ { fmt.Println(i) } // key value pairs kvs := map[string]string{ "name": "Scotch", "website": "https://scotch.io", } for key, value := range kvs { fmt.Println(key, value) } }
You can run the app in GoPlay Space.
Now that we know a little about the similarities and differences in language constructs, we can have a look at servers. Since we are coming from NodeJS it's likely that we're building a server, that returns JSON for instance.
In NodeJS, chances are while writing a server, you are using Express as the base library for your server. It's the most common, comes with a router and is the most battle tested. Here's a NodeJS server.
const express = require('express'); const app = express(); app.get('/', (req, res) => { res.send('Hello from Express!'); }) app.listen(3000, err => { if (err) { return console.log('something bad happened', err); } console.log(`server is listening on 3000`); })
Unlike JavaScript, the Go standard library provides everything we need to get a server up and running without any external dependencies. The net/http package provides most of this functionality. When building larger applications, expanding on the base net/http package with third-party packages is common, and one popular library that provides greatly expanded functionality is the Gorilla Web Toolkit.
Here's an equivalent Server in Go without any external library.
package main import ( "net/http" ) func Hello(w http.ResponseWriter, r *http.Request) { w.Write([]byte("Hello World")) } func main() { http.HandleFunc("/", Hello) if err := http.ListenAndServe(":8080", nil); err != nil { panic(err) } }
Things are starting to get interesting now.
if err != nil { // do something here // return err or panic panic(err) }
You can test this by running go run main.go, assuming your file was named main.go
Now, let's introduce a router library, because, if we don't, we'll have a lot of this in our code.
if req.Method == "POST" { // do this }
To get packages with golang, you usually use a go get <github-link>. To get Gorilla Mux from the Gorilla Web Toolkit we mentioned earlier, we would write the following in our terminal:
go get -u github.com/gorilla/mux
Then we are able to do this. I pulled this directly from Gorilla mux documentation.
package main import ( "fmt" "net/http" "github.com/gorilla/mux" ) func main() { r := mux.NewRouter() r.HandleFunc("/", HomeHandler) r.HandleFunc("/products", ProductsHandler) r.HandleFunc("/articles", ArticlesHandler) // details r.HandleFunc("/products/{key}", ProductHandler) r.HandleFunc("/articles/{category}/", ArticlesCategoryHandler) r.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler) http.Handle("/", r) } // example handler func ArticlesCategoryHandler(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) w.WriteHeader(http.StatusOK) fmt.Fprintf(w, "Category: %v\n", vars["category"]) }
We see that the same way express accepts patterns, Gorilla mux allows us to use the same patterns. It can get a little complicated than what I've described, but I hope you get the idea.
Gorilla mux also comes with helper functions that npm's body parser helps us achieve. Go purist can however claim that these function can easily be written.
Middleware are a great part of NodeJS servers.
They are functions that sit somewhere, and are run before the actual request is run. In NodeJS, this is a simple snippet for a middleware that retrieves a secret from the env and uses it to authenticate a user. When reading variables from NodeJS, dotenv is commonly used.
const express = require('express'); const app = express(); // add server_name middleware function authenticate((req, res, next) => { const secret = process.ENV.SECRET; if (secret == "") { return res.send("secret not found"); } if (!isAuthenticated(req, secret)) { return res.send("invalid authentication"); } return next(); }) app.get('/', authenticate, (req, res) => { res.send('Hello from Express!'); }) app.listen(3000, err => { if (err) { return console.log('something bad happened', err); } console.log(`server is listening on 3000`); })
Go takes a similar approach. Since all a middleware does is take in a request do, something with it and decide whether the request should proceed.
package main import ( "net/http" "os" ) // our sample authenticate middleware func Authenticate(next http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, r _http.Request) { secret := os.Getenv('SECRET') if len(secret) == 0 { w.Write(_[_]byte("secret not found") return } if !isAuthenticated(r, secret) { w.Write(_[_]byte("invalid authentication")) return } next.ServeHTTP(w, r) } func Hello(w http.ResponseWriter, r _http.Request) { w.Write([]byte("Hello World")) } func main() { http.HandleFunc("/", Authenticate(Hello)) // call the middeware by wrapping if err := http.ListenAndServe(":8080", nil); err != nil { panic(err) } }
If you are a seasoned JavaScript developer, you've probably noticed functions are first class citizens in Go too.
We've just written a function that takes in a [http.HandlerFunc](https://golang.org/pkg/net/http/#HandlerFunc) which is a function type, and the function structure is type HandlerFunc func(ResponseWriter, *Request), just like the Handler we wrote.
The advantage is that the http.HandlerFunc type has a function ServeHTTP which takes in the response and the request pointer we passed, and executes the handle call.
Some people call this approach wrapping functions, but this is the general idea. Again, you can easily write your own middlewares, but there are a couple of libraries out there to help you like http://www.gorillatoolkit.org/pkg/handlers and https://github.com/urfave/negroni.
Most of the time, our servers usually depend on an external API to get some data it needs. Let's say for example we are getting users from Github.
This is the approach you would take in a NodeJS app.
You'll first install a http request module, such as axios. npm install axios
const axios = require('axios'); const url = 'https://api.github.com/users'; axios.get(url).then(res => { // do something with the response }).catch(err => { // do something with the error })
This piece of code can either be in your service, or anywhere you like.
In Go, however, we do not need any external dependencies, and the net/http package can help us with this scenario.
package main import ( "fmt" "io/ioutil" "log" "net/http" ) func main() { URL := "https://api.github.com/users" res, err := http.Get(URL) if err != nil { log.Println(err) } defer res.Body.Close() // for garbage collection responseBodyBytes, err := ioutil.ReadAll(res.Body) if err != nil { log.Println(err) } fmt.Println(string(responseBodyBytes)) }
We use http.Get to make requests, and check errors. The response is usually in bytes, and we have to read it first, then convert it to string with strinb([]bytes).
You can add this to a main.go file and run go run main.go.
This code can also easily be converted to a func, and called repeatedly when needed.
NodeJS has various npm modules to help in database connections depending on the databases that you are using.
These libraries most of the time come with their own methods, that try to make it easier for you to work with them, and some even offer ORM like features.
Go however takes a different approach. The standard library provides an interface for working with databases called https://golang.org/pkg/database/sql/ which RDBMS package authors can use to implement drivers for various databases. Authors following the standard interface ensure greater interoperability for their packages.
Common database driver packages include: But to save you a lot of hustle, especially with SQL databases, https://github.com/jmoiron/sqlx will boost your productivity. Not to be left out of the ORM game either, the Go community has written many excellent ORMs such as https://github.com/jinzhu/gorm.
Go's files must be written within packages, and this usually affects your file structure.
In JavaScript, you'll see a lot of require statements at the beginning of files, while in Golang, the first line is always a package name, which will then be used as an import path in a file where it's required import package_path/package_name
I hope you've gotten a gist of what it's like to write Go, and you'd like to get into action. Golang is really praised for it's concurrency and performance, and if you are building a large application, this would be a preferred choice.
Here are some other cool stuff I did not cover, but are worth mentioning.
I've been following this transitional journey for a while now, and would glady answer any questions you may have. Just leave a comment.
Happy Go-ing! ;-)
via Scotch https://ift.tt/2yaUGB6
0 notes
Text
Send HIPAA Compliant Transactional Email with Node.js
Node.js Module for Paubox HIPAA Email API
The Paubox Node.js module allows you to construct and send secure, HIPAA compliant messages. This package is the official Node.js module for the Paubox HIPAA Compliant Transactional Email service.
The Paubox Transactional Email API allows your application to send secure, HIPAA compliant email via Paubox and track deliveries and opens.
Installation
Using npm:
$ npm install --save paubox-node
Getting Paubox API Credentials
You will need to have a Paubox account. You can sign up here.
Once you have an account, follow the instructions on the Rest API dashboard to verify domain ownership and generate API credentials.
Configuring API Credentials
Include your API credentials in your environment file.
$ echo "API_KEY='YOUR_API_KEY'" > .env $ echo "API_USERNAME='YOUR_ENDPOINT_NAME'" >> .env $ echo ".env" >> .gitignore
Usage
To send email, prepare a Message object and call the sendMessage method of emailService.
Sending messages
"use strict"; require('dotenv').config(); const pbMail = require('paubox-node'); const service = pbMail.emailService(); var options = { from: '[email protected]', to: ['[email protected]'], subject: 'Testing!', text_content: 'Hello World!', html_content: '
Hello World!
', } var message = pbMail.message(options) service.sendMessage(message) .then(response => { console.log("Send Message method Response: " + JSON.stringify(response)); }).catch(error => { console.log("Error in Send Message method: " + JSON.stringify(error)); });
Allowing non-TLS message delivery
If you want to send non-PHI mail that does not need to be HIPAA-compliant, you can allow the message delivery to take place even if a TLS connection is unavailable.
This means the message will not be converted into a secure portal message when a nonTLS connection is encountered. To do this, include allowNonTLS: true in the options, as shown below:
"use strict"; require('dotenv').config(); const pbMail = require('paubox-node'); const service = pbMail.emailService(); var options = { allowNonTLS: true, from: '[email protected]', to: ['[email protected]'], subject: 'Testing!', text_content: 'Hello World!', html_content: '
Hello World!
', } var message = pbMail.message(options)
Adding Attachments and Additional Headers
"use strict"; require('dotenv').config(); const pbMail = require('paubox-node'); const service = pbMail.emailService(); var attachmentContent = Buffer.from('Hello! This is the attachment content!').toString('base64') var options = { from: '[email protected]', reply_to: '[email protected]', to: ['[email protected]'], bcc: ['[email protected]'], subject: 'Testing!', text_content: 'Hello World!', html_content: '
Hello World!
', attachments: [{ fileName: "HelloWorld.txt", contentType: "text/plain", content: attachmentContent }] } var message = pbMail.message(options)
Checking Email Dispositions
The SOURCE_TRACKING_ID of a message is returned in the response of the sendMessage method. To check the status for any email, use its source tracking id and call the getEmailDisposition method of emailService:
"use strict"; require('dotenv').config(); const pbMail = require('paubox-node'); const service = pbMail.emailService(); service.getEmailDisposition("SOURCE_TRACKING_ID") .then(function (response) { console.log("Get Email Disposition method Response: " + JSON.stringify(response)); });
Contributing
Bug reports and pull requests are welcome on GitHub at https://github.com/paubox/paubox-node.
Not sure what to do next? Try Paubox API for FREE and make your transactional email HIPAA compliant today.
Start Your Free Trial
The post Send HIPAA Compliant Transactional Email with Node.js appeared first on Paubox.
Source: https://www.paubox.com/blog/hipaa-transactional-email-nodejs
0 notes
Photo

Well, this title may seem misleading. This is not an article regarding privacy of your apps or your content. We are not discussing how app companies are stealing your data and how you can prevent that. Actually, it seems a good thing to write on, saving it for next time!
So, what are we talking about? We are talking about how can we keep our secrets, data that we hold dear and do not want to disclose to anyone else, secure in a Nodejs application from a development perspective.
Let’s take a scenario where you are connecting with an external API using a bunch of ids and secret keys. You won’t believe but it is very much common that developers accidentally commit their keys in the code. And when someone comes sniffing around (which they do, always!), you are in serious trouble.
A simple yet effective way to go around this issue is using Environmental Variables!
We can store our secret keys and ids in environmental variables which the application can pick up once it runs. This way we do not compromise on security and have an easy access to the credentials as well. Also, since we do not hard-code the keys, we are more flexible with terms of using multiple credentials for troubleshooting.
How to do that? Pretty simple.
If you use the command line, then you can use export on a Macintosh or a Linux machine and if you are using Windows then you use set. Then your application as usual and you are ready to go!
export TECHUZAPIKEY=bccd321kjlo90alrn
If there are multiple environmental variables then the best thing to do is to create a .env file using the dotenv package and set all environmental variables you want in it. To retrieve the said variables you have to use the process.env object.
var mode = process.env.mode; // 'TESTING'
var TECHUZAPIKEY = process.env.TECHUZAPIKEY; // 'bccd321kjlo90alrn'
One thing to remember:
Never, ever commit your .env file to Source Control!
One way of ensuring that you do not commit your files to git for example is by adding a .env line to the .gitignore file.
Although this blog focuses on one particular aspect of environmental variables, we would like to highlight some of the best practises we follow at Techuz with respecting to coding in NodeJS so that it may benefit all:
1. Stay away from eval
Eval can play havoc especially with recent code injection attacks, never insert unvalidated input into the same.
2. Proper Session Management
Having proper flags for cookies can itself prevent attacks like cross-site scripting.
3. Using Retire.js
Retire.js will help you look for vulnerabilities within the module versions used.
4. Use IPTables
One can use IPTables redirect to redirect any request to a local port so that you do not have to run processes with superuser rights.
We at Techuz take security very seriously and all our code goes through stringent checks in order to see if it’s safe and secure. We constantly monitor new threats that emerge from around the globe and continuously evolve our security systems to tackle them.
Get in touch to know more or just say Hi!
0 notes